/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Describe：实现多语言的编辑窗口
* CreateTime：2020-04-07 21:03:38
* Version：1.0
* Modify Recorder：
*************************************************/

using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using TinyToolKit;
using TinyToolKit.Localization;
using System;
using System.IO;

namespace TinyToolKitEditor
{
    public class DrawWindowLanTrans : DrawWindowBase
    {
        private TinyToolEditorSettingAsset _toolSeting;

        public override void InitWindow(ScriptableObject setting)
        {
            _toolSeting = (TinyToolEditorSettingAsset)setting;
        }

        protected override void DrawInternalMainGUI()
        {
            if (_toolSeting.isEditMode == false)
            {
                if (TinyToolWindowUtil.DrawButton("新建"))
                {
                    _toolSeting.isEditMode = true;
                    ClearLanTrans();
                }
                if (TinyToolWindowUtil.DrawButton("打开"))
                {
                    ClearLanTrans();
                    _toolSeting.filePath = EditorUtility.OpenFilePanel("打开多国语言配置表", "Assets", "json");
                    if (_toolSeting.filePath.IsNullOrEmpty() == false)
                    {
                        int index = _toolSeting.filePath.IndexOf("Assets");
                        _toolSeting.filePath = _toolSeting.filePath.Remove(0, index);
                        _toolSeting.content = File.ReadAllText(_toolSeting.filePath);
                        if (_toolSeting.content.IsNullOrEmpty() == false)
                        {
                            _toolSeting.fileName = Path.GetFileNameWithoutExtension(_toolSeting.filePath);
                            _toolSeting.isEditMode = ParseJson(_toolSeting.content);
                        }
                    }
                }
            }
            else
            {
                DrawFileInfoArea();
                DrawLanguageArea();
                DrawCategoriesAndTrans();

                if (TinyToolWindowUtil.DrawButton("返回"))
                {
                    if (EditorUtility.DisplayDialog("警告", "确认退出编辑页面吗？修改的数据可能不会保存！", "确认", "取消"))
                    {
                        Clear();
                    }
                }
            }  
        }
        
        private void ClearLanTrans() 
        {
            _toolSeting.selectedLanCategory = 0;
            _toolSeting.lanCategories.Clear();
            _toolSeting.lanCategories.Add("None");
            _toolSeting.fileName = string.Empty;
            _toolSeting.filePath = string.Empty;
            _toolSeting.trans = new Translation();
        }

        private void DrawFileInfoArea() 
        {
            if (_toolSeting.fileName.IsNullOrEmpty() || _toolSeting.filePath.IsNullOrEmpty()) return;

            GUILayout.BeginVertical(EditorStyles.helpBox);
            EditorGUILayout.LabelField("文件名:", _toolSeting.fileName);
            EditorGUILayout.LabelField("路径:", _toolSeting.filePath);
            GUILayout.EndVertical();
        }

        private void DrawLanguageArea()
        {
            GUILayout.BeginVertical(EditorStyles.helpBox);
            GUILayout.Label("语言类型：", EditorStyles.boldLabel);
            _toolSeting.selectedLan = (Language)TinyToolWindowUtil.DrawEnumPopup("", _toolSeting.selectedLan);
            GUILayout.EndVertical();
        }

        private void DrawCategoriesAndTrans()
        {
            if (_toolSeting.selectedLan == Language.Unspecified) return;

            GUILayout.BeginVertical(EditorStyles.helpBox);
            GUILayout.Label("分类：", EditorStyles.boldLabel);

            EditorGUI.BeginDisabledGroup(_toolSeting.isEditCategories);
            _toolSeting.selectedLanCategory = TinyToolWindowUtil.DrawPopup(_toolSeting.selectedLanCategory, _toolSeting.lanCategories.ToArray());
            EditorGUI.EndDisabledGroup();  
            
            if (_toolSeting.isEditCategories == false)
            {
                if (_toolSeting.lanCategories.Count > _toolSeting.selectedLanCategory && _toolSeting.curCategory != _toolSeting.lanCategories[_toolSeting.selectedLanCategory])
                    _toolSeting.curCategory = _toolSeting.lanCategories[_toolSeting.selectedLanCategory];  

                if (GUILayout.Button("编辑", GUILayout.MaxWidth(70)))
                {
                    _toolSeting.isEditCategories = true;
                    _toolSeting.curCategory = "";
                }
            }
            else
            {
                _toolSeting.curCategory = GUILayout.TextField(_toolSeting.curCategory, GUILayout.MaxWidth(300));

                EditorGUILayout.BeginHorizontal();
                if (GUILayout.Button("添加", GUILayout.MaxWidth(70)))
                {
                    if (string.IsNullOrWhiteSpace(_toolSeting.curCategory) == false)
                    {
                        _toolSeting.isEditCategories = false;
                        AddCategories(_toolSeting.curCategory);
                    }
                }

                if (GUILayout.Button("替换", GUILayout.MaxWidth(70))) 
                {
                    _toolSeting.isEditCategories = false;
                    ReplaceCategories(_toolSeting.lanCategories[_toolSeting.selectedLanCategory], _toolSeting.curCategory); 
                }

                if (GUILayout.Button("删除", GUILayout.MaxWidth(70)))
                {
                    if (EditorUtility.DisplayDialog("删除分类", "确认要删除分类\"" + _toolSeting.curCategory + "\"及该分类下所有的翻译内容吗？", "删除", "取消"))
                    {
                        _toolSeting.isEditCategories = false;
                        RemoveCategories(_toolSeting.curCategory);
                    }
                }

                if (GUILayout.Button("取消", GUILayout.MaxWidth(70)))
                {
                    _toolSeting.isEditCategories = false;
                }
                EditorGUILayout.EndHorizontal();
            }
            GUILayout.EndVertical();

            if (_toolSeting.isEditCategories == false && _toolSeting.lanCategories[_toolSeting.selectedLanCategory] != "None")
                DrawTranslation();
        }
        
        private void DrawTranslation()
        {
            GUILayout.BeginVertical(EditorStyles.helpBox);

            TinyToolWindowUtil.DrawTableHead("关键字", "翻译");

            _toolSeting.removedKey.Clear();
            for (int i = 0; i < _toolSeting.trans.TransItems.Count; i++)
            {
                TranslationItem tranItem = _toolSeting.trans.TransItems[i];

                if (_toolSeting.selectedLanCategory <= _toolSeting.lanCategories.Count && tranItem.Category == _toolSeting.lanCategories[_toolSeting.selectedLanCategory])
                {
                    GUILayout.BeginHorizontal(EditorStyles.helpBox, GUILayout.MaxHeight(20));
                    tranItem.Key = EditorGUILayout.TextField(tranItem.Key,GUILayout.Width(140));
                    tranItem.Value = EditorGUILayout.TextArea(tranItem.Value);

                    //上移
                    if (GUILayout.Button("\u2191", GUILayout.Width(25))) 
                    {
                        if (i - 1 >= 0 && _toolSeting.trans.TransItems[i - 1].Category == tranItem.Category)
                        {
                            _toolSeting.trans.TransItems.RemoveAt(i);
                            _toolSeting.trans.TransItems.Insert(i - 1, tranItem);
                        }
                    }
                    //下移
                    if (GUILayout.Button("\u2193", GUILayout.Width(25))) 
                    {
                        if (i + 1 < _toolSeting.trans.TransItems.Count && _toolSeting.trans.TransItems[i + 1].Category == tranItem.Category)
                        {
                            _toolSeting.trans.TransItems.RemoveAt(i);
                            _toolSeting.trans.TransItems.Insert(i + 1, tranItem);
                        }
                    }
                    //删除
                    if (GUILayout.Button("\u00D7", GUILayout.Width(25))) 
                    {
                        if (EditorUtility.DisplayDialog("删除翻译", "你确定你要删除" + tranItem.Key + " ?", "删除", "取消"))
                        {
                            _toolSeting.removedKey.Add(tranItem);
                        }
                    }
                    GUILayout.EndHorizontal();
                    GUILayout.Space(2);
                }
            }

            for (int i = 0; i < _toolSeting.removedKey.Count; i++)
            {
                _toolSeting.trans.TransItems.Remove(_toolSeting.removedKey[i]);
            }

            if (TinyToolWindowUtil.DrawButton("添加"))
            {
                TranslationItem newTransItem = new TranslationItem(_toolSeting.lanCategories[_toolSeting.selectedLanCategory], "", "");

                bool hasInsert = false;
                for (int i = _toolSeting.trans.TransItems.Count - 1; i >= 0 ; i--)
                {
                    TranslationItem transItem = _toolSeting.trans.TransItems[i];
                    if (transItem.Category == newTransItem.Category)
                    {
                        hasInsert = true;
                        _toolSeting.trans.TransItems.Insert(i+1,newTransItem);
                        break;
                    }
                }

                if (hasInsert == false)
                    _toolSeting.trans.TransItems.Add(newTransItem);
            }

            GUILayout.EndVertical();
            
            string btnName = _toolSeting.filePath.IsNullOrEmpty() ? "创建配置表" : "更新配置表";
            if (TinyToolWindowUtil.DrawButton(btnName))
            {
                string savePath;
                if (_toolSeting.filePath.IsNullOrEmpty())
                {
                    savePath = EditorUtility.OpenFolderPanel("保存配置表", "Assets","");
                    if (string.IsNullOrEmpty(savePath)) return;

                    if (string.IsNullOrEmpty(_toolSeting.fileName))
                        _toolSeting.fileName = Enum.GetName(typeof(Language), _toolSeting.selectedLan);
                    savePath = Path.Combine(savePath, _toolSeting.fileName + ".json");

                    if (File.Exists(savePath))
                    {
                        File.Delete(savePath);
                    }
                    else
                    {
                        File.Create(savePath).Dispose();
                        SaveLanTransTable(savePath);
                    }
                }
                else//如果是打开文件，则直接保存原路径
                {
                    savePath = _toolSeting.filePath;
                    SaveLanTransTable(savePath);
                }
            }
        }

        private void SaveLanTransTable(string savePath)
        {
            _toolSeting.trans.Lan = _toolSeting.selectedLan;
            List<TranslationItem> tempTransItems = _toolSeting.trans.TransItems;
            _toolSeting.trans.TransItems = new List<TranslationItem>();
            for (int i = 0; i < _toolSeting.lanCategories.Count; i++)
            {
                for (int j = 0; j < tempTransItems.Count; j++)
                {
                    if (tempTransItems[j].Category == _toolSeting.lanCategories[i])
                    {
                        _toolSeting.trans.TransItems.Add(tempTransItems[j]);
                    }
                }
            }
            string content = JsonUtility.ToJson(_toolSeting.trans);
            if (string.IsNullOrEmpty(content) == false)
            {
                savePath = TinyUtility.Path.GetRegularPath(savePath);
                File.WriteAllText(savePath, content);
                EditorUtility.DisplayDialog("配置表保存成功", _toolSeting.fileName + ".json 保存在" + savePath, "确认");
            }
        }

        private bool ParseJson(string json)
        {
            Translation translation = JsonUtility.FromJson<Translation>(json);
            if (translation != null)
            {
                _toolSeting.trans = translation;
                _toolSeting.selectedLan = _toolSeting.trans.Lan;

                _toolSeting.lanCategories.Clear();
                for (int i = 0; i < _toolSeting.trans.TransItems.Count; i++)   
                {
                    TranslationItem item = _toolSeting.trans.TransItems[i];
                    if (_toolSeting.lanCategories.Contains(item.Category) == false)
                        _toolSeting.lanCategories.Add(item.Category);
                }

                if (_toolSeting.lanCategories.Count > 1)
                    _toolSeting.selectedLanCategory = 1;
                return true;
            }
            return false;
        }

        private void AddCategories(string categoryName)
        {
            if (_toolSeting.lanCategories.Contains(categoryName) == false)
                _toolSeting.lanCategories.Add(categoryName);
            else
                TinyToolWindowUtil.DrawWarnningDialog(categoryName + "存在已有分类中");

            _toolSeting.selectedLanCategory = _toolSeting.lanCategories.Count - 1;
        }

        private void ReplaceCategories(string categoryName,string newName)  
        {
            if (_toolSeting.lanCategories.Contains(categoryName))
            {
                _toolSeting.lanCategories.Remove(categoryName);
                _toolSeting.lanCategories.Add(newName); 
                for (int i = 0; i < _toolSeting.trans.TransItems.Count; i++)
                {
                    TranslationItem item = _toolSeting.trans.TransItems[i];
                    if (item.Category == categoryName)
                        item.Category = newName;
                }
            }
            else
                TinyToolWindowUtil.DrawWarnningDialog(categoryName + "不存在已有分类中");

            _toolSeting.selectedLanCategory = _toolSeting.lanCategories.Count - 1;
        }

        private void RemoveCategories(string categoryName) 
        {
            if (_toolSeting.lanCategories.Contains(categoryName))
            {
                _toolSeting.lanCategories.Remove(categoryName);
                List<TranslationItem> items = new List<TranslationItem>();
                for (int i = 0; i < _toolSeting.trans.TransItems.Count; i++)
                {
                    TranslationItem item = _toolSeting.trans.TransItems[i];
                    if (item.Category == categoryName && items.Contains(item) == false)
                        items.Add(item);
                }
                for (int i = 0; i < items.Count; i++)
                {
                    _toolSeting.trans.TransItems.Remove(items[i]);
                }
            }
            else
                TinyToolWindowUtil.DrawWarnningDialog(categoryName + "不存在已有分类中");

            _toolSeting.selectedLanCategory = _toolSeting.lanCategories.Count - 1;
        }

        private void Clear()
        {
            _toolSeting.selectedLan = 0;
            _toolSeting.selectedLanCategory = 0;
            _toolSeting.fileName = "";
            _toolSeting.filePath = "";
            _toolSeting.curCategory = string.Empty;
            _toolSeting.content = "";
            _toolSeting.isEditMode = false;
            _toolSeting.isEditCategories = false;
            _toolSeting.lanCategories.Clear();
            _toolSeting.trans = null;
            _toolSeting.removedKey.Clear();
        }
    }
}
